﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Gin.Transactions;
using System.IO;
using System.Xml.Serialization;

namespace Gin.Commands
{
    public class CreateFolder: TransactionalCommand
    {
        [GinArgumentText(Multiline = false, MaxLength = 500)]
        public string DestPath { get; set; }

        public bool CreateEmpty { get; set; }  
#warning тут надо доделать обработку

        public override void Do(ExecutionContext context)
        {
            DestPath = context.GetAbsolutePathFrom(DestPath);
            if (CreateEmpty)
            {
                Directory.Delete(DestPath, true);
            }
            Directory.CreateDirectory(DestPath);
        }

        public override TransactionStep Do(ExecutionContext context, Transaction transaction)
        {
            DestPath = context.GetAbsolutePathFrom(DestPath);
            SingleFileStep step = null;
            if (transaction != null)
            {
                step = transaction.CreateStep<SingleFileStep>(this);
            }
            if (Directory.Exists(DestPath))
            {
                string rollbackDirectoryName = Guid.NewGuid().ToString("N");
                string dataPath = step.GetPath(context);
                string rollbackDirectoryPath = Path.Combine(dataPath, rollbackDirectoryName);
                step.OldFilePath = rollbackDirectoryPath;
                Directory.Move(DestPath, rollbackDirectoryPath);
            }
            Do(context);
            return step;
        }

        public override void Rollback(TransactionStep step)
        {
            SingleFileStep currentStep = (SingleFileStep)step;
            if (Directory.Exists(currentStep.OldFilePath))
            {
                IOUtil.CopyDirectory(currentStep.OldFilePath, DestPath);
            }
            else
            {
                Directory.Delete(DestPath);
            }
        }
    }
}
